using UnityEngine;
using Unity.VisualScripting;
using GameFramework;
using GameFramework.DataTable;
using UnityGameFramework.Runtime;

namespace LS.UGFUnits
{
    [UnitShortTitle("Data Table")]
    [UnitSurtitle("Read Data")]
    public sealed class ReadDataTable : DataTableUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(DataRowBase))]
        public System.Type DataTableType { get; set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput DataTableInstance { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput AssetName { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput Priority { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput UserData { get; private set; }

        
        protected override void Definition()
        {
            AssetName =  ValueInput<string>(nameof(AssetName));
            DataTableInstance  = ValueInput<DataTableBase>(nameof(DataTableInstance));
            Priority = ValueInput<int>(nameof(Priority));
            UserData =  ValueInput<object>(nameof(UserData));
            Requirement(DataTableInstance, Input);
            Requirement(AssetName, Input);
            Requirement(UserData, Input);
            Requirement(Priority, Input);
        }

        protected override ControlOutput In(Flow flow)
        {
            string assetName = flow.GetValue<string>(AssetName);
            int priority = flow.GetValue<int>(Priority);
            DataTableBase dataTable = flow.GetValue<DataTableBase>(DataTableInstance);
            object userData = flow.GetValue<object>(UserData);
            if (dataTable != null)
            {
                dataTable.ReadData(assetName, priority, userData?? flow.stack.gameObject);
            }
            return base.In(flow);
        }
    }
}